package cn.juforg.gobang.interfaces.impl;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import cn.juforg.gobang.BaseAI;
import cn.juforg.gobang.BasePlayer;
import cn.juforg.gobang.Chess;
import cn.juforg.gobang.ChessBoard;
import cn.juforg.gobang.Line;
import cn.juforg.gobang.R;
import cn.juforg.gobang.interfaces.ChessBoardDao;

public class ChessBoardImpl implements ChessBoardDao {

	@Override
	public void setStatus(ChessBoard chessBoard, char newStatus) {
		ChessBoard.setCurrentStatus(newStatus);
//		TextView tv = chessBoard.getTextView();
    	if(newStatus==ChessBoard.PLAYER_TWO_LOST){
			//提示玩家2输了
//			tv.setText(R.string.player_two_lost);;
			newStatus = ChessBoard.READY;
		}else if(newStatus==ChessBoard.RUNNING){
//			tv.setText(null);
		}else if(newStatus==ChessBoard.READY){
//			tv.setText(R.string.status_ready);
		}else if(newStatus==ChessBoard.PLAYER_ONE_LOST){
			//提示玩家1输了
//			tv.setText(R.string.player_one_lost);
			ChessBoard.setCurrentStatus(ChessBoard.READY);
		}		
//    	chessBoard.setTextView(tv);
	}

	@Override
	public boolean isMyTurn(BasePlayer player, boolean currentPlayer) {
		if(player!=null){
			return player.getMyChessFlag()==currentPlayer;
		}
		return false;
	}
	
	@Override
	public void drawChssboardLines(List<Line> lines ,Canvas canvas, Paint paint) {
    	for (Line line : lines) {
    		canvas.drawLine(line.getXstart(), line.getYstart(), line.getXstop(), line.getYstop(), paint);
		}
	}

	@Override
	public void drawChess(Canvas canvas, char[][] chessArray,
			Bitmap[] chessColorArray, Paint paint) {
			for (int i = 0; i < ChessBoard.getMaxX(); i++) {
				for (int j = 0; j < ChessBoard.getMaxY(); j++) {
					if(chessArray[i][j]!='4'){
						int a = chessArray[i][j]-48;
						canvas.drawBitmap(chessColorArray[a],i*ChessBoard.getChessSize()
							+ChessBoard.getxOffset(),j*ChessBoard.getChessSize()+ChessBoard.getyOffset(),paint);
					
					}
				}
			}
			drawWeight(canvas, chessArray);
	}
	public void drawWeight(Canvas canvas,char[][] chessArray) {
		for (int i = BaseAI.CalculateRange.xstart; i <= BaseAI.CalculateRange.xstop; i++) {
			for (int j = BaseAI.CalculateRange.ystart; j <= BaseAI.CalculateRange.ystop; j++) {
//				if(chessArray[i][j]!='4'){
					
					drawWeight(canvas, i, j);
					
//				}
			}
		}
	}
	public void drawWeight(Canvas canvas,int i, int j){
	        Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	        numPaint.setTextSize(ChessBoard.chessSize);
	        numPaint.setColor(Color.GREEN);
	        numPaint.setTextAlign(Align.CENTER);
	        canvas.drawText(""+BaseAI.weights[i][j], (float)(i+0.5)*ChessBoard.getChessSize(), (j+1)*ChessBoard.getChessSize(), numPaint);
	        BaseAI.weights[i][j]= 0;
	}
	@Override
	public void restart(ChessBoard chessBoard) {
		char[][] c = new char[ChessBoard.getMaxX()][ChessBoard.getMaxY()];
	     for (int i = 0; i < ChessBoard.getMaxX(); i++) {
				for (int j = 0; j < ChessBoard.getMaxY(); j++) {
					c[i][j] = '4';
				}
			}
		chessBoard.setChessArray(c);
		ChessBoard.setPlayer1newchs(null);
		ChessBoard.setPlayer2newchs(null);
		BaseAI.CalculateRange.xstart = ChessBoard.maxX;
		BaseAI.CalculateRange.xstop = 0;
        BaseAI.CalculateRange.ystart = ChessBoard.maxY;
        BaseAI.CalculateRange.ystop = 0;
		this.setPlayerRun(chessBoard,true);
		this.refressCanvas(chessBoard);
	}

	@Override
	public boolean isRunning(char currentStatus) {
		if(currentStatus == ChessBoard.RUNNING){
			return true;
		}
		return false;
		
	}

	@Override
	public synchronized void playerRun(BasePlayer player, MotionEvent event) {
	
	}

	@Override
	public synchronized void playerRun(BasePlayer player, Chess chess, final ChessBoard chessBoard) {
			Log.i("old_currentPlayer", chessBoard.getCurrentPlayer()?"player1":"player2");
			if(this.setChess(chessBoard, chess, player.getMyChessFlag())){
			chessBoard.setCurrentPlayer(!chessBoard.getCurrentPlayer());
			this.refressCanvas(chessBoard);
			if(player.hasWin(chess, player.getMyChessFlag(), chessBoard.getChessArray())){
				this.setStatus(chessBoard, player.getMyChessFlag()?ChessBoard.PLAYER_TWO_LOST:ChessBoard.PLAYER_ONE_LOST);
				new  AlertDialog.Builder(chessBoard.getAty())
				.setTitle(R.string.game_over)  
				.setMessage(player.getMyChessFlag()?R.string.player_two_lost:R.string.player_one_lost)  
				.setPositiveButton(R.string.restart ,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								restart(chessBoard);
					        	ChessBoard.chssboddao.setStatus(chessBoard, ChessBoard.RUNNING);
								dialog.dismiss();
								}
							}
				        )  
				.setNegativeButton(R.string.return_menu , 
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								chessBoard.getAty().finish();
								dialog.dismiss();
						}
					}
				)
				.show();
			}
			generateCalculateRange(chess);//产生计算边界值（提高AI效率）
			Log.i("new_currentPlayer", chessBoard.getCurrentPlayer()?"player1":"player2");
			}
	}

	@Override
	public void playerRun(BasePlayer player, MotionEvent event, ChessBoard chessBoard) {
		Chess chess = this.generateChess(event.getX(), event.getY(), chessBoard);
		this.playerRun(player, chess, chessBoard);
	}

	@Override
	public Chess generateChess(Float x, Float y,ChessBoard chessBoard) {
		Chess  chess = new Chess(0,0);
		for(int i = 0; i <= ChessBoard.getMaxX();i++){
			if((i*ChessBoard.getChessSize()+ChessBoard.getxOffset()) <= x 
					&& x<= ((i+1)*ChessBoard.getChessSize()+ChessBoard.getxOffset())){
				chess.setX(i);
				break;
			}
		}
		for(int i = 0; i <= ChessBoard.getMaxY();i++){
			if((i*ChessBoard.getChessSize()+ChessBoard.getyOffset()) <= y 
					&& y<= ((i+1)*ChessBoard.getChessSize()+ChessBoard.getyOffset())){
				chess.setY(i);
				break;
			}
		}
		return chess;
	}

	@Override
	public void setPlayerRun(BasePlayer player) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void refressCanvas(ChessBoard chessBoard) {
		chessBoard.invalidate();		
	}

	@Override
	public void fillChessArrays(Bitmap[] chessColorArray, int color,
			Drawable drawable, int chessSize) {
		 Bitmap bitmap = Bitmap.createBitmap(chessSize, chessSize, Bitmap.Config.ARGB_8888);
	        Canvas canvas = new Canvas(bitmap);
	        drawable.setBounds(0, 0, chessSize, chessSize);
	        drawable.draw(canvas);
	        chessColorArray[color] = bitmap;
	}

	@Override
	public void setPlayerRun(ChessBoard chessBoard, boolean playerFlag) {
		chessBoard.setCurrentPlayer(playerFlag);
	}

	@Override
	public boolean setChess(ChessBoard chessBoard, Chess chess, boolean playerFlag) {
		if ('4' == chessBoard.getChessArray()[chess.getX()][chess.getY()]) {
			if (ChessBoard.PLAYER1FLAG == playerFlag) {
				if (null != ChessBoard.getPlayer1newchs()) {
					chessBoard.getChessArray()[ChessBoard.getPlayer1newchs()
							.getX()][ChessBoard.getPlayer1newchs().getY()] = ChessBoard.BLACK;
				}
				ChessBoard.setPlayer1newchs(chess);
				chessBoard.getChessArray()[chess.getX()][chess.getY()] = ChessBoard.NEW_BLACK;
			} else if (ChessBoard.PLAYER2FLAG == playerFlag) {
				if (null != ChessBoard.getPlayer2newchs()) {
					chessBoard.getChessArray()[ChessBoard.getPlayer2newchs()
							.getX()][ChessBoard.getPlayer2newchs().getY()] = ChessBoard.WHITE;
				}
				ChessBoard.setPlayer2newchs(chess);
				chessBoard.getChessArray()[chess.getX()][chess.getY()] = ChessBoard.NEW_WHITE;
			}
			return true;
		}
		return false;
			
	}

	public void generateCalculateRange(Chess chess){
		if(chess.getX()<=BaseAI.CalculateRange.xstart){
			if ((chess.getX()-2)>=0) {
				BaseAI.CalculateRange.xstart=chess.getX()-2;
			}else if ((chess.getX()-1)>=0) {
				BaseAI.CalculateRange.xstart=chess.getX()-1;
			} else {
				BaseAI.CalculateRange.xstart=chess.getX();
			}
		}
		if (chess.getX()>=BaseAI.CalculateRange.xstop ) {
			if ((chess.getX()+2)<=ChessBoard.maxX) {
				BaseAI.CalculateRange.xstop=chess.getX()+2;
			} else if ((chess.getX()+1)<=ChessBoard.maxX) {
				BaseAI.CalculateRange.xstop=chess.getX()+1;
			} else {
				BaseAI.CalculateRange.xstop=chess.getX();
			}
		}
		if(chess.getY()<=BaseAI.CalculateRange.ystart){
			if ((chess.getY()-2)>=0) {
				BaseAI.CalculateRange.ystart=chess.getY()-2;
			} else if ((chess.getY()-1)>=0) {
				BaseAI.CalculateRange.ystart=chess.getY()-1;
			} else {
				BaseAI.CalculateRange.ystart=chess.getY();
			}
		}
		if (chess.getY()>=BaseAI.CalculateRange.ystop) {
			if ((chess.getY()+2)<=ChessBoard.maxY) {
				BaseAI.CalculateRange.ystop=chess.getY()+2;
			} else if ((chess.getY()+1)<=ChessBoard.maxY) {
				BaseAI.CalculateRange.ystop=chess.getY()+1;
			} else {
				BaseAI.CalculateRange.ystop=chess.getY();
			}
		}
		Log.i("calculateRang", "x:"+BaseAI.CalculateRange.xstart+"-->"+BaseAI.CalculateRange.xstop);
		Log.i("calculateRang", "Y:"+BaseAI.CalculateRange.ystart+"-->"+BaseAI.CalculateRange.ystop);
	}


}
